package com.ltkj.baseplatform.service.impl;

import com.ltkj.baseplatform.domain.SerCollectData;
import com.ltkj.baseplatform.domain.SerCommentData;
import com.ltkj.baseplatform.domain.SerLikesData;
import com.ltkj.baseplatform.domain.SerTravelNotes;
import com.ltkj.baseplatform.domain.bo.SerTravelNotesBo;
import com.ltkj.baseplatform.domain.vo.SerTravelNotesVo;
import com.ltkj.baseplatform.mapper.SerCollectDataMapper;
import com.ltkj.baseplatform.mapper.SerCommentDataMapper;
import com.ltkj.baseplatform.mapper.SerLikesDataMapper;
import com.ltkj.baseplatform.mapper.SerTravelNotesMapper;
import com.ltkj.baseplatform.service.ISerTravelNotesService;
import com.ltkj.common.core.constant.CacheConstants;
import com.ltkj.common.core.domain.R;
import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.exception.auth.NotLoginException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.system.api.RemoteFileService;
import com.ltkj.system.api.domain.CommAttachment;
import com.ltkj.system.api.domain.CommAttachmentQueryVo;
import com.ltkj.system.api.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 游记管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-03
 */
@Service
public class SerTravelNotesServiceImpl implements ISerTravelNotesService {
    @Autowired
    private SerTravelNotesMapper serTravelNotesMapper;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SerCollectDataMapper serCollectDataMapper;

    @Autowired
    private SerCommentDataMapper serCommentDataMapper;

    @Autowired
    private SerLikesDataMapper serLikesDataMapper;

    /**
     * 查询游记管理
     *
     * @param id 游记管理主键
     * @return 游记管理
     */
    @Override
    public SerTravelNotes selectSerTravelNotesById(Long id) {
        return serTravelNotesMapper.selectSerTravelNotesById(id);
    }
    /**
     * 查询游记详情（小程序）
     *
     * @param id 游记主键
     * @return 游记
     */
    @Override
    public SerTravelNotesVo selectAppletTravelNotesById(Long id) {
        SerTravelNotesVo serTravelNotesVo = serTravelNotesMapper.selectSerTravelNotesVoById(id);
        //默认图片
        String infoCode = "travel_notes-file";
        //0文章/1视频
        /*if ("1".equals(serTravelNotesVo.getType())) {
            infoCode = "travel_notes-video";
        }*/
        List<CommAttachment> attachments = remoteFileService.selectAtta(serTravelNotesVo.getId(), infoCode);

        if(!CollectionUtils.isEmpty(attachments) && attachments.size() > 0){
            //取第一张图片展示
            CommAttachment commAttachment = attachments.get(0);
            //设置封面图片路径
            serTravelNotesVo.setImgPath(commAttachment.getAttaPath());
        }
        //拼接图片服务器的地址
        /*for (CommAttachment item : attachments) {
            if(StringUtils.hasText(item.getAttaPath())){
                item.setAttaPath(fileServerUrl + item.getAttaPath());
            }
            if(StringUtils.hasText(item.getAttaZoomPath())){
                item.setAttaZoomPath(fileServerUrl + item.getAttaZoomPath());
            }
        }*/
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long currUserId = loginUser != null ? loginUser.getUserid() : null;
        //登录内显示是否点赞或者收藏
        if(currUserId != null){
            //查询当前用户是否收藏
            SerCollectData serCollectData = new SerCollectData();
            serCollectData.setBizId(id);
            serCollectData.setTypeCode("travel");
            serCollectData.setUserId(currUserId);
            int count = serCollectDataMapper.selectCountByOptions(serCollectData);
            if(count > 0){
                serTravelNotesVo.setHasCollect(true);
            }
            //查询当前用户是否点赞
            SerLikesData serLikesData = new SerLikesData();
            serLikesData.setBizId(id);
            serLikesData.setTypeCode("travel");
            serLikesData.setUserId(currUserId);
            int likeCount = serLikesDataMapper.selectCountByOptions(serLikesData);
            if(likeCount > 0){
                serTravelNotesVo.setHasLikes(true);
            }
        }
        serTravelNotesVo.setAttachmentList(attachments);
        serTravelNotesVo.setFileType(serTravelNotesVo.getType());
        return serTravelNotesVo;
    }

    /**
     * 查询游记管理列表
     *
     * @param serTravelNotes 游记管理
     * @return 游记管理
     */
    @Override
    public List<SerTravelNotesVo> selectSerTravelNotesList(SerTravelNotes serTravelNotes) {
        return serTravelNotesMapper.selectSerTravelNotesVoList(serTravelNotes);
    }

    /**
     * 新增游记管理
     *
     * @param serTravelNotes 游记管理
     * @return 结果
     */
    @Override
    public int insertSerTravelNotes(SerTravelNotes serTravelNotes) {
        serTravelNotes.setCreateTime(DateUtils.getNowDate());
        serTravelNotes.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        serTravelNotes.setUserId(SecurityUtils.getUserId());
        return serTravelNotesMapper.insertSerTravelNotes(serTravelNotes);
    }

    /**
     * 修改游记管理
     *
     * @param serTravelNotes 游记管理
     * @return 结果
     */
    @Override
    public int updateSerTravelNotes(SerTravelNotes serTravelNotes) {
        serTravelNotes.setUpdateTime(DateUtils.getNowDate());
        serTravelNotes.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        return serTravelNotesMapper.updateSerTravelNotes(serTravelNotes);
    }

    /**
     * 批量删除游记管理
     *
     * @param ids 需要删除的游记管理主键
     * @return 结果
     */
    @Override
    public int deleteSerTravelNotesByIds(Long[] ids) {
        //return serTravelNotesMapper.deleteSerTravelNotesByIds(ids);
        int i = serTravelNotesMapper.updateDelFlagByIds(ids);
        if (i > 0){
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
            SerCollectData serCollectData = null;
            //批量删除的数据不会很多
            for (Long id : ids) {
                serCollectData = new SerCollectData();
                serCollectData.setBizId(id);
                serCollectData.setIsDel("1");
                serCollectData.setTypeCode("travel");
                serCollectDataMapper.updateDelFlagByBizCode(serCollectData);
            }
        }
        return i;
    }

    /**
     * 删除游记管理信息
     *
     * @param id 游记管理主键
     * @return 结果
     */
    @Override
    public int deleteSerTravelNotesById(Long id) {
        return serTravelNotesMapper.deleteSerTravelNotesById(id);
    }

    @Override
    public List<SerTravelNotesVo> selectAppletTravelNotesList(SerTravelNotes serTravelNotes) {
        List<SerTravelNotesVo> serTravelNotesVos = serTravelNotesMapper.selectSerTravelNotesVoList(serTravelNotes);
        if (!CollectionUtils.isEmpty(serTravelNotesVos)) {
            List<Long> ids = serTravelNotesVos.stream().map(item -> item.getId()).collect(Collectors.toList());
            //根据id查询附件列表
            //List<CommAttachment> commAttachments = serTravelNotesMapper.selectCommAttachmentList(ids);
            //根据多个业务id查询附件列表
            CommAttachmentQueryVo attachmentQueryVo = new CommAttachmentQueryVo();
            attachmentQueryVo.setInfoIds(ids);
            attachmentQueryVo.setInfoCode("travel_notes-file");
            R<List<CommAttachment>> result = remoteFileService.selectAttaByInfoIds(attachmentQueryVo);
            if (com.ltkj.common.core.utils.StringUtils.isNull(result) || com.ltkj.common.core.utils.StringUtils.isNull(result.getData())) {
                throw new ServiceException("附件查询服务异常！");
            }
            List<CommAttachment> commAttachments = result.getData();
            if (!CollectionUtils.isEmpty(commAttachments)){
                //根据业务id分组
                Map<Long, List<CommAttachment>> groupMap = commAttachments.stream().collect(
                        Collectors.groupingBy(CommAttachment::getInfoId));
                //给游记设置附件
                for (SerTravelNotesVo serTravelNotesVo : serTravelNotesVos) {
                    List<CommAttachment> attachments = groupMap.get(serTravelNotesVo.getId());
                    if(CollectionUtils.isEmpty(attachments) || attachments.size() == 0){
                        continue;
                    }

                    //取第一张图片展示
                    CommAttachment commAttachment = attachments.get(0);
                    //设置封面图片路径
                    if ("0".equals(serTravelNotesVo.getType()) && StringUtils.hasText(commAttachment.getAttaZoomPath())) { //0文章/1视频
                        //图片的话，查询列表，取缩略图,没有缩略图获取大图
                        serTravelNotesVo.setImgPath(commAttachment.getAttaZoomPath());
                    }else{
                        serTravelNotesVo.setImgPath(commAttachment.getAttaPath());
                    }

                    //拼接图片服务器的地址
                   /* for (CommAttachment item : attachments) {
                        if(StringUtils.hasText(item.getAttaPath())){
                            item.setAttaPath(item.getAttaPath());
                        }
                        if(StringUtils.hasText(item.getAttaZoomPath())){
                            item.setAttaZoomPath(item.getAttaZoomPath());
                        }
                    }*/
                    serTravelNotesVo.setAttachmentList(attachments);

                    serTravelNotesVo.setFileType(serTravelNotesVo.getType());
                }
            }
        }

        return serTravelNotesVos;
    }

    /**
     * 新增游记（小程序）
     *
     * @param serTravelNotesBo 游记管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAppletTravelNotes(SerTravelNotesBo serTravelNotesBo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser == null){
            throw new NotLoginException("用户未登录！");
        }
        SerTravelNotes serTravelNotes = new SerTravelNotes();
        BeanUtils.copyProperties(serTravelNotesBo, serTravelNotes);
        serTravelNotes.setCreateTime(DateUtils.getNowDate());
        serTravelNotes.setCreateBy(loginUser.getUsername());
        serTravelNotes.setUserId(loginUser.getUserid());
        int sum = serTravelNotesMapper.insertSerTravelNotes(serTravelNotes);
        //添加数据成功，且有上传图片执行操作
        if (sum > 0 && StringUtils.hasText(serTravelNotesBo.getAttachIds())) {
            //默认图片
            String infoCode = "travel_notes-file";
            //0文章/1视频
            /*if ("1".equals(serTravelNotes.getType())) {
                infoCode = "travel_notes-video";
            }*/
            //业务id与业务主键关联
            AjaxResult ajaxResult = remoteFileService.updateAttaData(serTravelNotes.getId(), infoCode, serTravelNotesBo.getAttachIds());
            if (ajaxResult == null || !"200".equals(ajaxResult.get("code").toString())) {
                throw new ServiceException("文件服务异常!");
            }
        }
        if (sum > 0){
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
        }
        return sum;
    }

    /**
     * 修改游记（小程序）
     *
     * @param serTravelNotesBo 游记管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAppletTravelNotes(SerTravelNotesBo serTravelNotesBo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser == null){
            throw new NotLoginException("用户未登录！");
        }
        SerTravelNotes serTravelNotes = new SerTravelNotes();
        BeanUtils.copyProperties(serTravelNotesBo, serTravelNotes);
        serTravelNotes.setUpdateTime(DateUtils.getNowDate());
        serTravelNotes.setUpdateBy(loginUser.getUsername());
        int sum = serTravelNotesMapper.updateSerTravelNotes(serTravelNotes);
        //添加数据成功，且有上传图片执行操作
        if (sum > 0 && StringUtils.hasText(serTravelNotesBo.getAttachIds())) {

            SerCollectData serCollectData = new SerCollectData();
            serCollectData.setBizId(serTravelNotes.getId());
            serCollectData.setTypeCode("travel");
            //设置一些文章的属性
            serCollectData.setAddr(serTravelNotes.getAddr());
            serCollectData.setViewNum(serTravelNotes.getViewNum());
            serCollectData.setTitle(serTravelNotes.getTitle());
            serCollectData.setLatitude(serTravelNotes.getLatitude());
            serCollectData.setLongitude(serTravelNotes.getLongitude());
            serCollectData.setIsDel(serTravelNotes.getIsDel());
            serCollectDataMapper.updateDelFlagByBizCode(serCollectData);

            //默认图片
            String infoCode = "travel_notes-file";
            //0文章/1视频
            /*if ("1".equals(serTravelNotes.getType())) {
                infoCode = "travel_notes-video";
            }*/
            //业务id与业务主键关联
            AjaxResult ajaxResult = remoteFileService.updateAttaData(serTravelNotes.getId(), infoCode, serTravelNotesBo.getAttachIds());
            if (ajaxResult == null || !"200".equals(ajaxResult.get("code").toString())) {
                throw new ServiceException("文件服务异常!");
            }
        }
        if (sum > 0){
            //综合推荐缓存
            redisService.deleteObject(CacheConstants.HOME_TAB_DATA_KEY);
        }
        return sum;
    }

    @Override
    public int updateViewNum(Long id) {
        return serTravelNotesMapper.updateViewNum(id);
    }

    @Override
    public int updateCommentNum(Integer num, Long id) {
        return serTravelNotesMapper.updateCommentNum(num,id);
    }

    @Override
    public int updateLikeNum(Integer num, Long id) {
        return serTravelNotesMapper.updateLikeNum(num,id);
    }

    //游记点赞
    @Override
    @Transactional
    public int addLikes(Long id) {
        SerLikesData serLikesData = new SerLikesData();
        serLikesData.setBizId(id);
        serLikesData.setTypeCode("travel");
        serLikesData.setUserId(SecurityUtils.getLoginUser().getUserid());
        serLikesData.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        serLikesData.setCreateTime(DateUtils.getNowDate());
        int num = serLikesDataMapper.insertSerLikesData(serLikesData);
        if(num > 0){
            serTravelNotesMapper.updateLikeNum(1,id);
        }
        return num;
    }
    //游记取消点赞
    @Override
    @Transactional
    public int cancelLikes(Long id) {
        int num = serLikesDataMapper.deleteLikesDataByBizIdAndCode(id, "travel");
        if(num > 0){
            serTravelNotesMapper.updateLikeNum(-1,id);
        }
        return num;
    }

    @Override
    @Transactional
    public int addCollect(SerCollectData serCollectData,SerTravelNotes serTravelNotes) {
        serCollectData.setTypeCode("travel");
        serCollectData.setUserId(SecurityUtils.getLoginUser().getUserid());
        serCollectData.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        serCollectData.setCreateTime(DateUtils.getNowDate());
        //设置游记的其他属性
        serCollectData.setAddr(serTravelNotes.getAddr());
        serCollectData.setViewNum(serTravelNotes.getViewNum());
        serCollectData.setTitle(serTravelNotes.getTitle());
        serCollectData.setLatitude(serTravelNotes.getLatitude());
        serCollectData.setLongitude(serTravelNotes.getLongitude());
        serCollectData.setIsDel(serTravelNotes.getIsDel());

        int num = serCollectDataMapper.insertSerCollectData(serCollectData);
        if(num > 0){
            //收藏量 +1
            serTravelNotesMapper.updateCollectNum(1,serCollectData.getBizId());
        }
        return num;
    }

    @Override
    @Transactional
    public int cancelColect(Long id) {
        int num = serCollectDataMapper.deleteCollectDataByBizIdAndCode(id, "travel");
        if(num > 0){
            //评论量 -1
            serTravelNotesMapper.updateCollectNum(-1,id);
        }
        return num;
    }

    @Override
    @Transactional
    public int publishComment(SerCommentData serCommentData) {
        if(serCommentData.getBizId() == null){
            throw new ServiceException("请输入业务编号！");
        }
        serCommentData.setTypeCode("travel");
        serCommentData.setUserId(SecurityUtils.getLoginUser().getUserid());
        serCommentData.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        serCommentData.setCreateTime(DateUtils.getNowDate());
        int num = serCommentDataMapper.insertSerCommentData(serCommentData);
        if(num > 0){
            //评论量 +1
            serTravelNotesMapper.updateCommentNum(1,serCommentData.getBizId());
        }
        return num;
    }

    @Override
    @Transactional
    public int deleteComment(Long id) {
        SerCommentData serCommentData = serCommentDataMapper.selectSerCommentDataById(id);
        int num = serCommentDataMapper.deleteSerCommentDataById(id);
        if(num > 0){
            //评论量 -1
            serTravelNotesMapper.updateCommentNum(-1,serCommentData.getBizId());
        }
        return num;
    }
}
